import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { apiBaseUrl } from '../../config';
import { message } from 'antd';

// 定义通用响应格式类型
interface CommonResponse<T> {
  code: number;
  data: T;
  msg: string;
}

// 获取MAC地址的工具函数
export async function getMacAddress(): Promise<string | null> {
  try {
    // 在Electron环境中，通过IPC调用主进程获取MAC地址
    if (typeof window !== 'undefined' && window.require) {
      const { ipcRenderer }: { ipcRenderer: Electron.IpcRenderer } = window.require('electron');
      const result = await ipcRenderer.invoke('get-mac-address');
      if (result.success) {
        return result.data;
      } else {
        console.error('获取MAC地址失败:', result.error);
        return null;
      }
    } else {
      // 在非Electron环境中，返回null
      console.warn('非Electron环境，无法获取MAC地址');
      return null;
    }
  } catch (error) {
    console.error('获取MAC地址时发生错误:', error);
    return null;
  }
}

// 获取所有MAC地址的工具函数
export async function getAllMacAddresses(): Promise<string[]> {
  try {
    if (typeof window !== 'undefined' && window.require) {
      const { ipcRenderer }: { ipcRenderer: Electron.IpcRenderer } = window.require('electron');
      const result = await ipcRenderer.invoke('get-all-mac-addresses');
      if (result.success) {
        return result.data;
      } else {
        console.error('获取所有MAC地址失败:', result.error);
        return [];
      }
    } else {
      console.warn('非Electron环境，无法获取MAC地址');
      return [];
    }
  } catch (error) {
    console.error('获取所有MAC地址时发生错误:', error);
    return [];
  }
}

class Request {
    private instance: AxiosInstance;
    private token: string | null = null;

    constructor(baseURL: string) {
        this.instance = axios.create({
            baseURL,
            timeout: 10000,
            headers: {
                'Content-Type': 'application/json',
            },
        });

        // 请求拦截器
        this.instance.interceptors.request.use(
            (config) => {
                // 如果有token，添加到请求头
                if (this.token) {
                    config.headers.Authorization = `Bearer ${this.token}`;
                }
                return config;
            },
            (error) => {
                return Promise.reject(error);
            }
        );

        // 响应拦截器
        this.instance.interceptors.response.use(
            (response: any) => {
                const { code, msg } = response.data;
                switch (code) {
                    case 0:
                        // 成功响应，直接返回 response.data
                        return response.data;
                    case -1:
                        message.error(msg);
                        break;
                    default:
                        message.error('未知错误');
                }
                // 可以在这里处理通用的响应逻辑
                return response.data;
            },
            (error) => {
                // 处理错误响应
                if (error.response) {
                    switch (error.response.status) {
                        case 401:
                            // Token过期或无效，可以跳转到登录页
                            window.location.href = '/login';
                            break;
                        case 404:
                            message.error('请求的资源不存在');
                            break;
                        case 500:
                            message.error('服务器错误');
                            break;
                        default:
                            message.error('未知错误');
                    }
                }
                return Promise.reject(error);
            }
        );
    }

    // 设置Token
    public setToken(token: string): void {
        this.token = token;
        // 可以在这里将token存储到localStorage或electron-store中
        localStorage.setItem('token', token);
    }

    // 清除Token
    public clearToken(): void {
        this.token = null;
        localStorage.removeItem('token');
    }

    // 检查是否有Token
    public hasToken(): boolean {
        return !!this.token || !!localStorage.getItem('token');
    }

    // 初始化时从存储中加载Token
    public loadToken(): void {
        const token = localStorage.getItem('token');
        if (token) {
            this.token = token;
        }
    }

    // GET请求
    public async get<T>(url: string, config?: AxiosRequestConfig): Promise<CommonResponse<T>> {
        return this.instance.get(url, config);
    }

    // POST请求
    public async post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<CommonResponse<T>> {
        return this.instance.post(url, data, config);
    }

    // PUT请求
    public async put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<CommonResponse<T>> {
        return this.instance.put(url, data, config);
    }

    // DELETE请求
    public async delete<T>(url: string, config?: AxiosRequestConfig): Promise<CommonResponse<T>> {
        return this.instance.delete(url, config);
    }
}

// 创建实例并导出
const baseURL = apiBaseUrl;
const request = new Request(baseURL);

// 初始化时加载token
request.loadToken();

// 获取用户浏览器数量
export async function getUserBrowserNum(): Promise<number> {
  try {
    const res = await request.get<{ browser_num: number }>('get_user_browser_num');
    if (res.code === 0 && typeof res.data.browser_num === 'number') {
      return res.data.browser_num;
    } else {
      throw new Error(res.msg || '获取浏览器数量失败');
    }
  } catch (error) {
    throw new Error(error instanceof Error ? error.message : '获取浏览器数量失败');
  }
}

// 获取用户信息
export async function getUserInfo(): Promise<{ username: string; expire_time: string }> {
  try {
    const res = await request.get<{ username: string; expire_time: string }>('get_user_info');
    if (res.code === 0 && res.data) {
      return res.data;
    } else {
      throw new Error(res.msg || '获取用户信息失败');
    }
  } catch (error) {
    throw new Error(error instanceof Error ? error.message : '获取用户信息失败');
  }
}

// 浏览器配置接口类型
export interface BrowserConfigApi {
  id: number;
  cookie: string;
  browser_config: string;
  update_time: string;
  instance_id: string;
  create_time: string;
  username: string;
}

// 获取浏览器列表
export async function getBrowserList(): Promise<BrowserConfigApi[]> {
  try {
    const res = await request.get<{ browser_list: BrowserConfigApi[] }>('get_browser_list');
    if (res.code === 0 && res.data && Array.isArray(res.data.browser_list)) {
      return res.data.browser_list;
    } else {
      throw new Error(res.msg || '获取浏览器列表失败');
    }
  } catch (error) {
    throw new Error(error instanceof Error ? error.message : '获取浏览器列表失败');
  }
}

// 添加浏览器
export async function addBrowser(instance_id: string, browser_config: string): Promise<any> {
  try {
    const res = await request.post('add_browser', {
      instance_id,
      browser_config
    });
    if (res.code === 0) {
      return res;
    } else {
      throw new Error(res.msg || '添加浏览器失败');
    }
  } catch (error) {
    throw new Error(error instanceof Error ? error.message : '添加浏览器失败');
  }
}

// 编辑浏览器
export async function editBrowser(instance_id: string, browser_config: string): Promise<any> {
  try {
    const res = await request.post('edit_browser', {
      instance_id,
      browser_config
    });
    if (res.code === 0) {
      return res;
    } else {
      throw new Error(res.msg || '编辑浏览器失败');
    }
  } catch (error) {
    throw new Error(error instanceof Error ? error.message : '编辑浏览器失败');
  }
}

// 删除浏览器
export async function deleteBrowser(instance_id: string): Promise<any> {
  try {
    const res = await request.post('delete_browser', {
      instance_id
    });
    if (res.code === 0) {
      return res;
    } else {
      throw new Error(res.msg || '删除浏览器失败');
    }
  } catch (error) {
    throw new Error(error instanceof Error ? error.message : '删除浏览器失败');
  }
}

// 获取浏览器 cookie
export async function getBrowserCookie(instance_id: string): Promise<{ cookie: string | null }> {
  try {
    const res = await request.get<{ cookie: string | null }>('get_browser_cookie', {
      params: { instance_id }
    });
    if (res.code === 0 && res.data) {
      return res.data;
    } else {
      throw new Error(res.msg || '获取浏览器cookie失败');
    }
  } catch (error) {
    throw new Error(error instanceof Error ? error.message : '获取浏览器cookie失败');
  }
}

// 报告 cookie 变化
export async function reportCookie(instance_id: string, cookie: string): Promise<any> {
  try {
    const res = await request.post('report_cookie', {
      instance_id,
      cookie
    });
    if (res.code === 0) {
      return res;
    } else {
      throw new Error(res.msg || '报告cookie失败');
    }
  } catch (error) {
    throw new Error(error instanceof Error ? error.message : '报告cookie失败');
  }
}

export default request;